package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.system.service.IProductTelemetryService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/product.v2")
public class ProductController extends BaseController {
    @Autowired
    IProductService productService;

    @Autowired
    IProductTelemetryService productTelemetryService;

    @Autowired
    TokenService tokenService;

    @Autowired
    ISysDeptService sysDeptService;

    @Autowired
    IDeviceService deviceService;

    private AjaxResult checkExistance(Product product) {
        Map<String, Object> existance = productService.findExistance(product);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "名称已经存在");
            }
            // Object code_exists = existance.get("code_exists");
            // if (code_exists != null && Integer.parseInt(code_exists.toString()) > 0) { 
            //     return AjaxResult.error(HttpStatus.ERROR, "产品型号已经存在");
            // }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @Log(title = "产品型号", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) Product product) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        product.setCompanyId(companyId);
        product.setCreateBy(createBy);
        product.setCreateTime(new Date());
        AjaxResult ret = checkExistance(product);
        if (ret != null) {
            return ret;
        }
        Integer id = productService.create(product);
        if (id != null) {
            return AjaxResult.success(product);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) Product product) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("name", product.getName());
        queryVo.filters.put("code", product.getCode());
        queryVo.filters.put("manufacturer", product.getManufacturer());
        queryVo.filters.put("description", product.getDescription());
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<Product> products = productService.index(queryVo);
        return getDataTable(products);
    }

    @PreAuthorize("@ss.hasPermi('system:product:enum')")
    @GetMapping(value = "/enum", produces = "application/json;charset=UTF-8")
    public AjaxResult enumerate() {
        QueryVo queryVo = new QueryVo();
        return AjaxResult.success(productService.enumerate(queryVo));
    }

    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Product product = productService.retrieve(queryVo);
        if (product == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(product);
    }

    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "产品型号", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) Product product) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", product.getId());
        Product target = productService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        product.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(product);
        if (ret != null) {
            return ret;
        }
        if (productService.update(product)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:device:remove')")
    @Log(title = "产品型号", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        // TODO: [ZY] check related modules
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());

        QueryVo preQueryVo = new QueryVo();
        preQueryVo.filters.put("product_id", id);
        preQueryVo.filters.put("company_id", companyId);
        //验证当前用户属于客户公司还是总公司
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            preQueryVo.filters.put("customer_name",loginUser.getUsername());
        }
        startPage();
        List<Device> devices = deviceService.index(preQueryVo);
        if (devices != null && devices.size() > 0) {
            return AjaxResult.error("系统中存在该型号的产品，不能删除该型号");
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("company_id", companyId);
        if (productService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
